const express = require('express')
const router = express.Router()
const models = require('../models')
const AlipayFormData = require('alipay-sdk/lib/form').default
const { success, error } = require('../utils/message')
const alipaySdk = require('../alipay/alipay-sdk')

// 支付
router.post('/pay', async function (req, res, next) {
  // 用户发送过来，需要支付的订单id
  const id = req.body.id

  // 检测订单是否已经支付
  const order = await models.Order.findByPk(id)
  if (order.status > 2) {
    return error(res, '订单已经支付，请勿重新付款')
  }

  const formData = new AlipayFormData()

  // 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
  formData.setMethod('get')

  formData.addField('notifyUrl', 'https://api.shop.clwy.cn')
  formData.addField('bizContent', {
    outTradeNo: order.outTradeNo,
    productCode: 'FAST_INSTANT_TRADE_PAY',
    totalAmount: order.totalPrice,
    subject: '长乐未央商城',
    body: '商品详情',
  })

  // 'alipay.trade.wap.pay',
  const result = await alipaySdk.exec(
    'alipay.trade.page.pay',
    {},
    { formData: formData },
  )

  success(res, '支付地址生成成功', { result })
})

// 验证回调
router.post('/notify', async function (req, res, next) {
  // https://www.yuque.com/chenqiu/alipay-node-sdk/notify_verify
  // https://github.com/alipay/alipay-sdk-nodejs-all/blob/master/test/alipay.test.js
  const verify = alipaySdk.checkNotifySign(req.body)
})


module.exports = router
